"""
Compreface集成模块
与远程Compreface人脸识别服务进行集成
"""

import requests
import numpy as np
from typing import Dict, List, Tuple, Optional


class ComprefaceManager:
    def __init__(self, api_key: str, server_url: str):
        """
        初始化Compreface管理器
        :param api_key: Compreface API密钥
        :param server_url: Compreface服务器地址
        """
        self.api_key = api_key
        self.server_url = server_url.rstrip('/')
        self.headers = {
            'x-api-key': self.api_key
        }
    
    def connect(self) -> bool:
        """
        连接到远程Compreface服务
        :return: 连接是否成功
        """
        try:
            response = requests.get(f"{self.server_url}/status", headers=self.headers)
            return response.status_code == 200
        except Exception as e:
            print(f"连接Compreface服务失败: {e}")
            return False
    
    def load_remote_faces(self) -> Dict[str, np.ndarray]:
        """
        从远程Compreface服务加载人脸数据
        :return: 人脸数据字典 {name: encoding}
        """
        # 这是一个简化的实现，实际的Compreface API可能需要不同的调用方式
        try:
            response = requests.get(f"{self.server_url}/api/faces", headers=self.headers)
            if response.status_code == 200:
                # 解析响应数据
                faces_data = response.json()
                face_database = {}
                # 这里需要根据实际的API响应格式进行解析
                return face_database
            else:
                print(f"加载远程人脸数据失败: {response.status_code}")
                return {}
        except Exception as e:
            print(f"加载远程人脸数据异常: {e}")
            return {}
    
    def upload_local_face(self, name: str, image_path: str) -> bool:
        """
        将本地人脸数据上传到远程Compreface服务
        :param name: 人员姓名
        :param image_path: 人脸图像路径
        :return: 上传是否成功
        """
        try:
            with open(image_path, 'rb') as f:
                files = {'file': f}
                data = {'name': name}
                response = requests.post(
                    f"{self.server_url}/api/faces",
                    headers=self.headers,
                    files=files,
                    data=data
                )
                return response.status_code == 200
        except Exception as e:
            print(f"上传人脸数据失败: {e}")
            return False
    
    def sync_faces(self, local_database: Dict[str, np.ndarray]) -> Dict[str, np.ndarray]:
        """
        同步本地与远程人脸库
        :param local_database: 本地人脸数据库
        :return: 合并后的人脸数据库
        """
        try:
            # 加载远程人脸数据
            remote_database = self.load_remote_faces()
            
            # 合并数据库（这里简单合并，实际可能需要更复杂的冲突解决机制）
            merged_database = {**remote_database, **local_database}
            return merged_database
        except Exception as e:
            print(f"同步人脸库失败: {e}")
            return local_database